package com.example.demo.controller;


import com.example.demo.entity.ResponseInfo;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

@RestController
@RequestMapping("/api/ocr")
@Slf4j
public class OCRController {
    private final Tesseract tesseract;

    public OCRController(Tesseract tesseract) {
        this.tesseract = tesseract;
    }

    @PostMapping("/recognize")
    public ResponseInfo<String> recognizeImage(@RequestParam("image") MultipartFile image, @RequestParam(value = "language", defaultValue = "chi_sim") String language) throws IOException, TesseractException {
        File convertedFile = convertMultipartFileToFile(image);
        tesseract.setLanguage(language);
        String result = tesseract.doOCR(convertedFile);
        log.info(result);
        return ResponseInfo.successInfo(result);
    }

    private File convertMultipartFileToFile(MultipartFile file) throws IOException {
        File convertedFile = new File(file.getOriginalFilename());
        try (OutputStream os = new FileOutputStream(convertedFile)) {
            os.write(file.getBytes());
        }
        return convertedFile;
    }
}
